<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

/**
 * 推广组事件
 */
Class AdgroupsEvent extends NewzanAction
{
   public function getIndexData($params)
   {
        $user_id = $params['user_id'];
        $index = $params['index'];
        $source = (int)$params['source'] == 1 ? 'AVG' : 'MAX';
        $from = $params['from'];
        $to = $params['to'];
        $data_source = $params['data_source'];
        $adgroupMdl = new AdgroupModel;

        $adgroup_iids = array();
        
        if(isset($params['adgroup_id']) && $params['adgroup_id']) {
            $adgroup_iids = explode(',', $params['adgroup_id']);
            unset($params['adgroup_id']);
        }
        if(isset($params['campaign_id']) && $params['campaign_id']) {
            $campaign_id = !is_array($params['campaign_id']) ? explode(',', $params['campaign_id']) : $params['campaign_id'];
            foreach ($campaign_id as $key => $id) {
                $tmp = $adgroupMdl->getCampaignsAdgroups($user_id, $id, false, $from, $to, false, 0, 0, array(), array('online_status' => 'online'));
                if($tmp)
                    $adgroup_iids = array_merge($adgroup_iids, array_column($tmp, 'adgroup_id'));
            }
            unset($tmp);
            unset($params['campaign_id']);
        }
        

        if(!$adgroup_iids) {
            $tmp = M('adgroups')
                                ->field('adgroups.adgroup_id')
                                ->join('campaigns ON campaigns.campaign_id = adgroups.campaign_id')
                                ->where(array(
                                        'adgroups.online_status' => 'online',
                                        'campaigns.online_status' => 'online',
                                        'adgroups.user_id' => $user_id
                                    ))
                                ->select();
            $adgroup_iids = array_column($tmp, 'adgroup_id');
            unset($tmp);
        }

        $data = $adgroupMdl->getForAdgroupIndex($user_id, $index, $source, $from, $to, $adgroup_iids, $data_source);
        if($source == 'MAX') {
            foreach ($data as $key => &$value) {
                $value = round($value, 2);
            }
        }
        // 缓存仅当天有效
        $save_time = strtotime(date('Y-m-d',strtotime('+1 day')))-time();
        S($sKey, $data, $save_time);
        return $data;
   }
}
